-----------------------------------------------------------------------------------------
--
-- main.lua
--
-----------------------------------------------------------------------------------------

-- Your code here

local startBlock
local canTransition = false
local function blockTouch(event)
	if event.phase == "began" then
		startBlock = event.target
		canTransition = true
	elseif event.phase == "moved" then
		if canTransition == false then
			return true
		end
		if startBlock == event.target then
			return true
		end
		if startBlock.x ~= event.target.x and startBlock.y ~= event.target.y then
			return true
		end
		local tranTime = 200
		startBlock:toFront()
		local afterTransition = function(obj)
			transition.to(startBlock, {time=tranTime, x=event.target.x, y=event.target.y})
			transition.to(event.target, {time=tranTime, x=startBlock.x, y=startBlock.y})
		end
		transition.to(startBlock, {time=tranTime, x=event.target.x, y=event.target.y})
		transition.to(event.target, {time=tranTime, x=startBlock.x, y=startBlock.y, onComplete=afterTransition})
		canTransition = false
	end
	return true
end

local function createBlocks()
	local colors = {{255, 0, 0}, {0, 255, 0}, {0, 0, 255}, {255, 255, 0}, {0, 255, 255}, {255, 0, 255}, {255, 255, 255}}
	
	local rowcount = 8
	local colcount = 8
	
	local blockWidth = display.contentWidth / colcount
	local blockHeight = display.contentWidth / rowcount
	
	local top = (display.contentHeight - display.contentWidth) / 2
	local row
	local col
	local pan = 3
	for row = 1, rowcount do
		for col = 1, colcount do
			local block = display.newRoundedRect((col - 1) * display.contentWidth / 8 + pan, top + (row - 1) * display.contentWidth / 8 + pan, blockWidth - pan * 2, blockHeight - pan * 2, 10)
			block:setFillColor(unpack(colors[math.random(1, #colors)]))
			block:addEventListener("touch", blockTouch)
		end
	end
end

local function main()
	createBlocks()
end

main()